import React, { Component } from 'react';
import { Card, Form, Input, Cascader, Upload, Button } from 'antd';
import { ArrowLeftOutlined } from '@ant-design/icons';
import LinkButton from '../../components/link-button';
import PicturesWall from './pictures-wall';
import RichTextEditor from './rich-text-editor';
const { TextArea } = Input;

let allData = [{
    "_id": {
      "$oid": "5e12b8bce31bb727e4b0e348"
    },
    "parentId": "0",
    "name": "家用电器",
    "__v": 0
  },{
    "_id": {
      "$oid": "5e130e60e31bb727e4b0e34b"
    },
    "parentId": "0",
    "name": "手机",
    "__v": 0
  },{
    "_id": {
      "$oid": "5e130ec7e31bb727e4b0e34c"
    },
    "parentId": "0",
    "name": "洗衣机",
    "__v": 0
  },{
    "_id": {
      "$oid": "5e1346533ed02518b4db0cd7"
    },
    "parentId": "0",
    "name": "图书",
    "__v": 0
  },{
    "_id": {
      "$oid": "5e13467e3ed02518b4db0cd8"
    },
    "parentId": "0",
    "name": "杯具",
    "__v": 0
  },{
    "_id": {
      "$oid": "5e1346c83ed02518b4db0cd9"
    },
    "parentId": "0",
    "name": "纸",
    "__v": 0
  },{
    "_id": {
      "$oid": "5e144dc7297c1138787e96ab"
    },
    "parentId": "0",
    "name": "服装",
    "__v": 0
  },{
    "_id": {
      "$oid": "5e144de1297c1138787e96ac"
    },
    "parentId": "0",
    "name": "玩具",
    "__v": 0
  },{
    "_id": {
      "$oid": "5e16e37e49dc6b38d018fe28"
    },
    "parentId": "0",
    "name": "手机",
    "__v": 0
  },{
    "_id": {
      "$oid": "5e16e38949dc6b38d018fe29"
    },
    "name": "三星",
    "__v": 0,
    "parentId": "0"
  },{
    "_id": {
      "$oid": "5fc0bf33eb957f1b94f4a959"
    },
    "parentId": "0",
    "name": "医药",
    "__v": 0
  },{
    "_id": {
      "$oid": "5fc0bfa4eb957f1b94f4a95a"
    },
    "parentId": "0",
    "name": "食品",
    "__v": 0
  },{
    "_id": {
      "$oid": "5fc0bfcdeb957f1b94f4a95b"
    },
    "parentId": "0",
    "name": "发型",
    "__v": 0
  },{
    "_id": {
      "$oid": "5fc0bfd7eb957f1b94f4a95c"
    },
    "parentId": "0",
    "name": "水果",
    "__v": 0
  },{
    "_id": {
      "$oid": "5fc0bfdeeb957f1b94f4a95d"
    },
    "parentId": "0",
    "name": "发饰",
    "__v": 0
  },{
    "_id": {
      "$oid": "5fc0bfe6eb957f1b94f4a95e"
    },
    "parentId": "0",
    "name": "图纸",
    "__v": 0
  },{
    "_id": {
      "$oid": "5fc30a1833fe4221c4546275"
    },
    "parentId": "5e12b8bce31bb727e4b0e348",
    "name": "冰箱",
    "__v": 0
  },{
    "_id": {
      "$oid": "5fc30a4133fe4221c4546276"
    },
    "parentId": "5e12b8bce31bb727e4b0e348",
    "name": "微波炉",
    "__v": 0
  },{
    "_id": {
      "$oid": "5fc30a4a33fe4221c4546277"
    },
    "parentId": "5e12b8bce31bb727e4b0e348",
    "name": "电饭煲",
    "__v": 0
  },{
    "_id": {
      "$oid": "5fc30a5133fe4221c4546278"
    },
    "parentId": "5e12b8bce31bb727e4b0e348",
    "name": "洗衣机",
    "__v": 0
  },{
    "_id": {
      "$oid": "5fc30a6533fe4221c4546279"
    },
    "parentId": "5e12b8bce31bb727e4b0e348",
    "name": "消毒碗柜",
    "__v": 0
  },{
    "_id": {
      "$oid": "5fc30a6f33fe4221c454627a"
    },
    "parentId": "5e12b8bce31bb727e4b0e348",
    "name": "电视",
    "__v": 0
  },{
    "_id": {
      "$oid": "5fc30a7a33fe4221c454627b"
    },
    "parentId": "5e12b8bce31bb727e4b0e348",
    "name": "抽油烟机",
    "__v": 0
  },{
    "_id": {
      "$oid": "5fc5a5ff4870c82a702c5efd"
    },
    "parentId": "0",
    "name": "bbb",
    "__v": 0
  },{
    "_id": {
      "$oid": "5fc5b24b4870c82a702c5f05"
    },
    "parentId": "0",
    "name": "2",
    "__v": 0
  },{
    "_id": {
      "$oid": "5fc5b2ae4870c82a702c5f06"
    },
    "parentId": "0",
    "name": "34",
    "__v": 0
  },{
    "_id": {
      "$oid": "5fc5b2b84870c82a702c5f07"
    },
    "parentId": "5fc5b2ae4870c82a702c5f06",
    "name": "222",
    "__v": 0
  },{
    "_id": {
      "$oid": "5fc74b650dd9b10798413162"
    },
    "parentId": "5e12b8bce31bb727e4b0e348",
    "name": "电脑",
    "__v": 0
  },{
    "_id": {
      "$oid": "5fc9e7cc618171388c09b7eb"
    },
    "parentId": "0",
    "name": "哈哈哈",
    "__v": 0
  }];

allData.forEach(v => v['_id'] = v['_id']['$oid']);




class Save extends Component {

    formRef = React.createRef();

    state = {
        options: [],
    };

    constructor(props){
      super(props);
      this.editor = React.createRef();
    }

    /**
     * 表单提交
     * @param {*} values 
     */
    submit = (values) => {
        console.log('提交：', values);
        // 调用子组件方法获取
        const detail = this.editor.current.getDetail();
        console.log('detail:',detail);
    }

    /**
     * 异步获取一级/二级分类列表
     */
    getCategorys = (parentId) => {
        const categorys = allData.filter(v => v.parentId === parentId);
        // 若为一级分类列表
        if(parentId === '0'){
            this.initOptions(categorys);
        }else{
            // 二级列表
            return categorys;
        }
    }

    /**
     * 级联选择器数据初始化
     * @param {*} categorys 
     */
    initOptions = (categorys) => {
        // 根据categorys生成options数组
        const options = categorys.map(c => ({
            value: c['_id'],
            label: c.name,
            isLeaf: false  //先假设不是叶子
        }));
        
        // 若回显显示子级列表
        const { isUpdate, product } = this;
        const { pCategoryId, categoryId } = product;
        if(isUpdate && pCategoryId !== '0'){
            // 获取对应二级分类列表
            const subCategorys = this.getCategorys(pCategoryId);
            // 生成级联选择器的子级options
            // 未考虑有n级子级
            const childOptions = subCategorys.map(c => ({
                value: c['_id'],
                label: c.name,
                isLeaf: true 
            }));
            // 知道当前商品对应的一级option对象上
            const targetOption = options.find(option => option.value === pCategoryId);
            // 关联对应的一级option上
            targetOption.children = childOptions;
        }

        // 更新options状态
        this.setState({
            options
        });
    }


    /**
     * 商品价格验证
     * @param {*} rule 
     * @param {*} value 
     * @param {*} callback 
     */
    validatePrice = (rule, value, callback) => {
        value * 1 > 0 ? callback() : callback('价格必须大于0');
    }


    /**用于加载下一级列表的回调函数
     * 
     * @param {*} selectedOptions 
     */
    loadData = selectedOptions => {
        // 得到选择的option对象
        const targetOption = selectedOptions[selectedOptions.length - 1];
        // 显示loading效果
        targetOption.loading = true;

        // 根据选中的分类，请求获取二级分类列表
        const subCategorys = this.getCategorys(targetOption.value);
        if(subCategorys && subCategorys.length > 0){
            const childOptions = subCategorys.map(c => ({
                value: c['_id'],
                label: c.name,
                isLeaf: true 
            }));
            // 关联到当前option上
            targetOption.children = childOptions;
        }else{
            // 当前选中的分类没有二级列表
            // isLeaf = true 不在加载下一级
            targetOption.isLeaf = true;
        }
        
        // 更新options
        setTimeout(() => {
            targetOption.loading = false;
            this.setState({
                options: [...this.state.options]
            });

        }, 1000);
        // load options lazily
        // setTimeout(() => {
        //     targetOption.loading = false;
        //     targetOption.children = [
        //         {
        //             label: `${targetOption.label} Dynamic 1`,
        //             value: 'dynamic1',
        //         },
        //         {
        //             label: `${targetOption.label} Dynamic 2`,
        //             value: 'dynamic2',
        //         },
        //     ];
        //     this.setState({
        //         options: [...options]
        //     });
        // }, 1000);
    };
    

    UNSAFE_componentWillMount(){
        // 修改时取state
        const product = this.props.location.state;
        // 巧妙的用法
        this.isUpdate = !!product;
        this.product = product || {};
    }


    componentDidMount(){
        // 初始化级联数据
        this.getCategorys('0');
    }

    // initialValues不动态更新解决方式
    componentDidUpdate() {
        // 表单回显
        if(this.product && this.product['_id']){
            this.formRef.current.setFieldsValue({
                name: this.product.name,
                desc: this.product.desc,
                price: this.product.price,
                // 过滤categoryId为空的情况
                categoryIds: [this.product.pCategoryId, this.product.categoryId ? this.product.categoryId : null].filter(Boolean),
                imgs: this.product.imgs,
                detail: this.product.detail
            });
        }
    }


    render() {

        const formItemLayout = {
            labelCol: { span: 2 },//左侧label的宽度
            wrapperCol: { span: 8 } //右侧包裹的宽度
        };

        const title = (
            <span>
                <LinkButton>
                    <ArrowLeftOutlined
                        style={{ marginRight: '5px', fontSize: '18px' }}
                        // props.history.goBack() 后退
                        onClick={() => this.props.history.goBack()}
                    />
                </LinkButton>
                <span>商品{this.isUpdate ? '修改' : '添加'}</span>
            </span>
        );


        return (
            <Card title={title}>
                <Form
                    {...formItemLayout}
                    ref={this.formRef}
                    onFinish={this.submit}
                >
                    <Form.Item
                        label="商品名称"
                        name="name"
                        rules={[{ required: true, message: '商品名称不能为空' }]}
                    >
                        <Input placeholder='输入商品名称' />
                    </Form.Item>

                    <Form.Item
                        label="商品描述"
                        name="desc"
                        rules={[{ required: true, message: '商品描述不能为空' }]}
                    >
                        <TextArea
                            placeholder='输入商品描述'
                            autoSize={{ minRows: 4, maxRows: 6 }}
                        />
                    </Form.Item>
                    <Form.Item
                        label="商品价格"
                        name="price"
                        rules={[
                            { required: true, message: '商品价格不能为空' },
                            { validator: this.validatePrice }
                        ]}
                    >
                        <Input type='number' placeholder='输入商品价格' addonAfter='元' />
                    </Form.Item>
                    <Form.Item
                        label="商品分类"
                        name="categoryIds"
                        rules={[{ required: true, message: '商品分类不能为空' }]}
                    >
                        <Cascader
                            // 需要显示的列表数据
                            options={this.state.options}
                            // 当选择某个列表项，加载下一级列表的监听回调
                            loadData={this.loadData}
                            placeholder='选择商品分类'
                        />
                    </Form.Item>
                    <Form.Item
                        label="商品图片"
                        rules={[{ required: true, message: '商品图片不能为空' }]}
                    >
                        <PicturesWall />
                    </Form.Item>
                    <Form.Item
                        label="商品详情"
                        rules={[{ required: true, message: '商品详情不能为空' }]}
                        labelCol={{ span: 2 }}
                        wrapperCol={{ span: 8 }}
                    >
                        <RichTextEditor ref={this.editor} detail={this.product.detail} />
                    </Form.Item>
                    <Form.Item>
                        <Button type="primary" htmlType="submit">提 交</Button>
                    </Form.Item>
                </Form>
            </Card>
        );
    }
}

export default Save;